<template>
  <div>
    <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-form ref="formData" :model="formData" label-width="175px" :rules="rules" v-loading="loading" :element-loading-text="loadingText">
        <el-row type="flex" justify="space-around">
          <el-col :span="12">
            <el-form-item label="Advanced Notice Hours"  prop="advanced_notice_hours">
              <el-select placeholder="Please Select A Advanced Notice Hours" v-model="formData.advanced_notice_hours" style="margin-left: 30px;">
                <el-option :label="num" :value="num" v-for="num in hoursList"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Allow Request to Book"   prop="advanced_notice_allow_request_to_book">
              <el-switch v-model="formData.advanced_notice_allow_request_to_book">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" justify="space-around">
          <el-col :span="24">
            <el-form-item label="Distant Request Days" prop="distant_requests_days">
              <el-input placeholder="Please Enter Distant Request Days" class="input-size" style="width:50%; margin-right: 10px;"
                        v-model="formData.distant_requests_days" :disabled="chooseDaysFlag !== '1'">
              </el-input>
              <el-radio-group v-model="chooseDaysFlag" style="width:48%; float:right;" @change="changeDaysFlag">
                <el-radio-button label="-1" >Any</el-radio-button>
                <el-radio-button label="0" >Not Allowed</el-radio-button>
                <el-radio-button label="1"><i class="el-icon-circle-check"></i></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" justify="space-around">
          <el-col :span="12">
            <el-form-item label="Turn Over Days"  prop="turn_over_days">
              <el-input-number  placeholder="Please Enter Turn Over Days" v-model="formData.turn_over_days" :step="1" :min="0" :max="2"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>

        <el-divider content-position="left">
          Seasonal Min Nights
          <el-button type="primary" icon="el-icon-plus" circle  @click="addMinNight"></el-button>
          <el-button type="success" icon="el-icon-edit" circle  @click="editMinNight"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="deleteMinNights"></el-button>
        </el-divider>


        <el-row type="flex" justify="space-around">
          <el-col :span="1"></el-col>
          <el-col :span="23" style="text-align: left;">
            <el-transfer  :titles="['Source', 'Target']"   filterable v-model="checkDatas" :data="minNightDatas"
            @change="handleChange"  :render-content="renderFunc"></el-transfer>
          </el-col>
        </el-row>

        <el-form-item style="text-align: center;margin-top:40px;">
          <el-button type="primary" @click="doSave">Save Changes</el-button>
          <el-button @click="doClose">Close</el-button>
          <el-button type="danger"  @click="doSynchro">更新可定规则</el-button>
        </el-form-item>
      </el-form>

    </el-scrollbar>

    <el-dialog title="Rule Info" :visible.sync="dialogFormVisible" width="30%">
      <el-form ref="minNightData" :model="minNightData"  label-width="175px" :rules="minNightRules" v-loading="minNightLoading" :element-loading-text="minNightLoadingText">
        <el-form-item label="Rule Name" prop="rule_name">
          <el-input v-model="minNightData.rule_name"   placeholder="Please Enter Rule Name" maxlength="64"></el-input>
        </el-form-item>

        <el-form-item label="Date Range"  prop="dateRange">
          <div class="block" style="width: 100%">
            <el-date-picker ref="dateRange" style="width: 100%"  class="input-size"
                              v-model="minNightData.dateRange"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="-"
                            start-placeholder="Start Date"
                            end-placeholder="End Date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                             @change="changeDateRange"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item label="Min Nights" prop="min_nights">
          <el-input-number v-model="minNightData.min_nights"  style="width: 100%"  :min="1" :max="100"   placeholder="Please Enter Min Nights"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doCloseDialog">Close</el-button>
        <el-button type="primary" @click="doSaveMinNight">Save Changes</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
    import {addModel,searchModel,get,updateModel,deleteModel,addModels,updateModels} from "@/api/model";
    import {submitAction} from "@/api/task";
    export default {
        name: "EditAvailabilityRulesForm",
        props:["pid"],
        data() {
            return {
                model: 'PhysicalRoomAvailabilityRule', //
                model2: 'PhysicalRoomSeasonalMinNights', //
                bodyHeight:900,
                dialogFormVisible: false,
                hoursList:[],
                chooseDaysFlag: [],
                cacheMinNightDatas:[],
                minNightDatas: [],
                checkDatas: [],
                selMinNightId: null, //选中的MinNightId
                formData: this.getInitFormData(),
                parentObj : null, //父对象
                loading:false,
                loadingText:'data load ...',
                rules: this.getInitRules(),
                minNightLoading: false,
                minNightLoadingText:'Data Saving ... ',
                minNightData:this.getInitMinNightData(),
                minNightRules: this.getInitMinNightRules(),
                dateRangeErr: null
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
        },
        mounted(){
            for(let num = 0; num <= 24; num++){
                this.hoursList.push(num);
            }
            this.hoursList.push(48);
            this.hoursList.push(72);
            this.hoursList.push(168);
        },
        methods: {

            getInitFormData(){
                return  {
                    id: null,
                    physical_room_hook:this.pid,  //   Hook    PhysicalRoom的外链
                    advanced_notice_hours:null,  //   整数  允许的值0-24, 48, 72, 168。
                    advanced_notice_allow_request_to_book:true,  //   布尔值 在
                    distant_requests_days:0,  //   整数  -1：允许预订未来任意日期 0：不允许预订未来任何日期  正整数：只允许预定未来这么多天以内的日期
                    turn_over_days:0,  //  整数  允许值：0，1，2．
                    seasonal_min_nights_hook:null,  //  Hook  PhysicalRoomSeasonalMinNights的多对多外链
                };
            },
            getInitRules() {
                const _this = this;
                const custRulesCfg = this.getCustRulesConfig();
                const distant_requests_daysValid = custRulesCfg.intValid('Distant Request Days',-1,10000);

                return {
                    advanced_notice_hours:[
                        { required: true, message: 'Please Select A Cancelation Policy', trigger: 'change' }
                    ],
                    advanced_notice_allow_request_to_book:[
                        { required: true, message: 'Please Select A Allow Request to Book', trigger: 'change' }
                    ],
                    distant_requests_days:[
                        { required: true, validator:distant_requests_daysValid, trigger: 'blur' }
                    ],
                    turn_over_days:[
                        { required: true, message: 'Please Select A Turn Over Days', trigger: 'blur' }
                    ]
                };
            },
            getCustRulesConfig(){
                return {
                    intValid: function(label, min, max){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseInt(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an integer value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an integer value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    callback();
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }
                        };
                        return intValidFun;
                    },
                    floatValid: function(label, min, max,custCb){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseFloat(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an float value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an float value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    if(custCb){
                                        custCb(rule, value, callback);
                                    }else{
                                        callback();
                                    }
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }

                        };
                        return intValidFun;
                    },
                };
            },
            refresh(_parentObj){
                console.log("refresh to do ...");
                this.parentObj = _parentObj;
                this.loadDatas();
            },
            /**
             * 加载数据
             */
            loadDatas(){
                console.log("loadDatas to do ...");
                this.doReset();
                this.loading = true;

                this.loadMinNights(()=>{
                    this.loadRules();
                });
            },
            loadMinNights(callback){
                let _this = this;
                searchModel(this.model2, {
                    search_keys:{}
                }).then(res => {
                    console.log("callback");
                    console.log(callback);
                    if(callback) callback();
                    _this.loading = false;
                    if(!res || !res.data){
                        return;
                    }
                    const list = res.data.list;
                    if(!list  || list.length == 0){
                        return;
                    }
                    _this.fillMinNightDatas(list);
                }).catch(reason => {
                    if(callback) callback();
                    _this.loading = false;
                    console.error(reason);
                });
            },
            fillMinNightDatas(list){
                console.log(list);
                this.cacheMinNightDatas = list;
                this.minNightDatas = this.cacheMinNightDatas.map(item => {
                    const _id = item.id;
                    const _rule_name = item.rule_name;
                   return {key: _id,label:_rule_name};
                });
            },
            loadRules(){
                let _this = this;
                const _pid = this.pid;
                searchModel(this.model, {
                    search_keys:{physical_room__physical_room_id: _pid}
                }).then(res => {
                    console.log("res===>");
                    console.log(res);
                    _this.loading = false;
                    if(!res || !res.data){
                        return;
                    }
                    const list = res.data.list;
                    if(!list  || list.length == 0){
                        return;
                    }
                    this.formData = list[0];
                    console.log("loadRules.then ...");
                    this.setTransferChecked();
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            setTransferChecked(){
                const _smnStr = this.formData.seasonal_min_nights_hook;
                if(!_smnStr){
                    return;
                }
                const _this = this;
                const arr = _smnStr.split(",");
                this.cacheMinNightDatas.forEach(item => {
                    const _rule_name = item.rule_name;
                    const _id = item.id;
                    for(let i=0, count=arr.length; i<count; i++){
                        if(arr[i] == _rule_name){
                            _this.checkDatas.push(_id);
                            break;
                        }
                    }
                });
                console.log(_this.checkDatas);
            },
            renderFunc(h, option) {
                var _this = this;
                return h(
                    'span', {
                        attrs: {
                            id: option.label
                        },
                        domProps: {
                            innerHTML: option.label
                        },
                        on: {
                            click: function () {
                                console.log("key="+option.key);
                                _this.selMinNightId = option.key;
                            }
                        }
                    }
                );
            },
            handleChange(value, direction, movedKeys) {
                console.log("=======  handleChange ==========");
                console.log(value, direction, movedKeys);
                if(direction == 'left'){
                    this.checkDatas = this.checkDatas.filter(key => {
                        if(movedKeys && movedKeys.length > 0){
                          for(let i=0, count=movedKeys.length; i<count; i++){
                              const _key = movedKeys[i];
                              if(_key == key){
                                  return false;
                              }
                          }
                        }
                       return true;
                    });
                }
                console.log("this.checkDatas2...");
                console.log(this.checkDatas);
            },
            /**
             * 保存数据
             */
            doSave(){
                console.log("doSave to do ...");
                const _this = this;
                console.log(this.formData);
                this.formData.physical_room_hook = this.pid;
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val){
                      if(val !== 0 || val !== '0') continue;
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                      /*
                        if(!_this.checkDatas || _this.checkDatas.length == 0){
                            _this.$message.error('Please Select Seasonal Min Nights!');
                            return;
                        }
                      */
                      console.log("checkDatas");
                      console.log(_this.checkDatas);
                      if(_this.checkDatas && _this.checkDatas.length > 0){
                        _this.formData.seasonal_min_nights_hook = _this.checkDatas.join(";");
                      }else{
                        delete _this.formData["seasonal_min_nights_hook"];
                      }

                      // if(!_this.formData.seasonal_min_nights_hook){
                      //   delete _this.formData["seasonal_min_nights_hook"];
                      //   console.log("_this.formData.seasonal_min_nights_hook="+_this.formData.seasonal_min_nights_hook);
                      // }
                        _this.loading = true;
                        if(_this.formData.id){
                            updateModel(this.model, _this.formData.id, _formData).then(res => {
                                _this.loading = false;
                                //_this.doSynchro();
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });

                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                //_this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }else{
                            const jsonStr =  JSON.stringify(_formData);
                            addModel(this.model, jsonStr).then(res => {
                                console.log(res);
                                const _id = res.data.id;
                                _this.formData.id = _id;
                                _this.loading = false;
                               // _this.doSynchro();
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });

                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                // _this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            doClose(){
                const _parent = this.parentObj ||  this.$parent;
                console.log(_parent);
                _parent.closeDrawer();
            },
            /**
             * 重置表单
             */
            doReset(){
                this.cacheMinNightDatas = [];
                this.minNightDatas = [];
                this.checkDatas = [];
                this.formData = this.getInitFormData();
                if(this.$refs['formData']) this.$refs['formData'].resetFields();
            },
            /**----------- Add Amenity Info Code Start ------------**/
            getInitMinNightData(_data){
                let _id = null;
                let _rule_name = null;	//字符串	最大120字符。规则的名字
                let _start_date = null;	//日期	规则开始日期
                let _end_date = null;	//日期	规则结束日期，不得比开始日期早。
                let _min_nights = 0;	//	整数	最小为1。最少需要入住的天数
                let _dateRange = [];
                if(_data){
                    _id = _data.id;
                    _rule_name = _data.rule_name;
                    _start_date = _data.start_date;
                    _end_date = _data.end_date;
                    _min_nights = _data.min_nights;
                    const startDate = new Date(_start_date.replace(/-/g, "\/"));
                    const endDate = new Date(_end_date.replace(/-/g, "\/"));
                    //_dateRange = [startDate,endDate];
                    _dateRange = [_start_date,_end_date];
                }
                return  {
                    id: _id,
                    rule_name: _rule_name,	//字符串	最大120字符。规则的名字
                    start_date: _start_date,	//日期	规则开始日期
                    end_date: _end_date,	//日期	规则结束日期，不得比开始日期早。
                    min_nights: _min_nights,	//	整数	最小为1。最少需要入住的天数
                    dateRange: _dateRange
                };
            },
            getInitMinNightRules() {
                const _this = this;
                const custRulesCfg = this.getCustRulesConfig();
                //dateRangeErr
                const dateRangeValidFun = (rule, value, callback) => {
                    if(this.dateRangeErr){
                        callback(new Error(this.dateRangeErr));
                    }else{
                        callback();
                    }
                };


                return {
                    rule_name: [
                        { required: true, message: 'Please Enter Rule Name', trigger: 'blur' },
                        { min: 1, max: 120, message: '1 to 120 characters in length', trigger: 'blur' }
                    ],
                    dateRange: [
                         { validator: dateRangeValidFun, trigger: 'blur'}
                        // { required: true, message: 'Please Select  Start Date And End Date', trigger: 'blur'}
                    ],
                    min_nights: [
                        { required: true, message: 'Please Enter Min Nights', trigger: 'change'}
                    ]
                };
            },
            /**
             * 添加 PhysicalRoomSeasonalMinNights
             */
            addMinNight(){
                console.log("addMinNight...");
                this.selMinNightId = null;
                this.doShowDialog();
            },
            changeDaysFlag(value){
                console.log("changeDaysFlag...");
                console.log(value);
                this.formData.distant_requests_days = value;
            },
            changeDateRange(value, v2, v3){
                if(!value || value.length == 0){
                    this.minNightData.start_date = null;
                    this.minNightData.end_date = null;
                }else{
                    const [_startDate, _endDate] = value;
                    this.minNightData.start_date = _startDate;
                    this.minNightData.end_date = _endDate;
                    this.dateRangeErr = null;
                }

                console.log("_startDate="+this.minNightData.start_date+", _endDate="+this.minNightData.end_date);
            },
            /**
             * 编辑 PhysicalRoomSeasonalMinNights
             */
            editMinNight(){
                const _this = this;
                console.log("editMinNight...");
                if(!_this.selMinNightId){
                    _this.$message.error('Please select a record to modify from the right!');
                    return;
                }
                const _datas = this.cacheMinNightDatas.filter(item => {
                    return item.id == _this.selMinNightId;
                });
                this.doShowDialog();
                this.minNightData = this.getInitMinNightData(_datas[0]);

            },
            /**
             * 删除 PhysicalRoomSeasonalMinNights
             */
            deleteMinNights(){
                const _this = this;
                console.log("deleteMinNights...");
                if(!_this.selMinNightId){
                    _this.$message.error('Please select a record to delete from the right!');
                    return;
                }
                _this.loading = true;
                deleteModel(this.model2, _this.selMinNightId).then(res => {
                    _this.loading = false;
                    _this.$message({
                        type: 'info',
                        message: 'Delete Data Success!'
                    });
                    _this.refresh();
                }).catch(reason => {
                    _this.loading = false;
                    console.log("deleteMinNights Failure...");
                    console.log(reason);
                    //_this.$message.error('Please Check Input Form Data Has Errors!');
                });

            },
            /**
             * 保存 PhysicalRoomSeasonalMinNights
             **/
            doSaveMinNight(){
                console.log("doSaveMinNight to do ...");
                const _this = this;
                console.log(this.minNightData);
                let _formData = this.minNightData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }
                // const _dateRange = _formData.dateRange;
                // const _firstDate = _dateRange[0];
                // const _lastDate = _dateRange[1];
                // const firstDate =  moment(_firstDate).format('YYYY-MM-DD');
                // const lastDate = moment(_lastDate).format('YYYY-MM-DD');
                // _formData.start_date = firstDate;
                // _formData.end_date = lastDate;
                delete _formData["dateRange"];
                const start_date = _formData.start_date;
                const end_date = _formData.end_date;
                if(start_date &&　end_date){
                   // this.$refs['dateRange'].clearValidate();
                    this.dateRangeErr = null;
                }else{
                    this.dateRangeErr = 'Please Select  Start Date And End Date';
                }

                this.$refs['minNightData'].validate((valid) => {
                    if (valid) {
                        _this.minNightLoading = true;
                        if(this.selMinNightId){ //修改
                            updateModel(this.model2, _this.minNightData.id, _formData).then(res => {
                                _this.minNightLoading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                _this.doCloseDialog();
                                _this.refresh();
                            }).catch(reason => {
                                _this.minNightLoading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                //_this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }else{//新增
                            const jsonStr =  JSON.stringify(_formData);
                            addModel(this.model2, jsonStr).then(res => {
                                console.log(res);
                                const _id = res.data.id;
                                _this.formData.id = _id;
                                _this.minNightLoading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                _this.doCloseDialog();
                                _this.refresh();
                            }).catch(reason => {
                                _this.minNightLoading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                 _this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            refresh(){
                this.loadMinNights(()=>{
                    this.loadRules();
                });
            },
            doShowDialog(){
                this.dialogFormVisible = true;
                this.minNightData = this.getInitMinNightData();
                if(this.$refs['minNightData']) this.$refs['minNightData'].resetFields();
            },
            /**
             * 关闭弹窗
             **/
            doCloseDialog(){
                this.minNightData = this.getInitMinNightData();
                if(this.$refs['minNightData']) this.$refs['minNightData'].resetFields();
                this.dialogFormVisible = false;
            },
            /**----------- Add Amenity Info Code End ------------**/
          /**
           * ActionTask ABNB API 同步
           */
          doSynchro(){
            const _this = this;
            const _id = this.formData.id;
            if(!_id){
              _this.$message.error(this.model+' id is null,Please Check Data...!');
              return;
            }
            //create_update_listing_description
            const actionName = "create_update_availability_rule";
            this.loadingText = "Calling API: "+actionName+" ...";
            this.loading = true;

            submitAction(this.model, _id,actionName).then(res => {
              this.loading = false;
              _this.$notify({
                title: 'Success',
                message: this.model+' Id:'+ _id +' call API:'+actionName+' succeeded !',
                type: 'success'
              });

            }).catch(reason => {
              _this.loading = false;
              console.log("deleteModel Failure...");
              console.error(reason);
              let errMsg = reason.data || reason.statusText;

              _this.$notify.error({
                title: 'Error',
                message: 'API:'+actionName+'  call error ,Error Reason:['+errMsg+']'
              });
              //_this.$message.error('Please Check Input Form Data Has Errors!');
            });
          }
        }
    }
</script>

<style scoped>
  .input-size{
    width: 85%;
  }
</style>

